package com.lanchetech.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lanchetech.bean.dto.*;
import com.lanchetech.bean.request.*;
import com.lanchetech.bean.response.*;
import com.lanchetech.common.util.HttpUtil;
import com.lanchetech.service.AgoraService;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.swing.tree.TreeNode;
import java.util.Base64;
import java.util.Map;
import java.util.TreeMap;

@Service
public class AgoraServiceImpl implements AgoraService {
    String appid = "8cc3e6be3564492d8cc8d84d11597eed";
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public String getToken() {

        return null;
    }

    @Override
    public String getAuthorization() {
        // 客户 ID
        final String customerKey = "928c4659a1644f78b87980aad3ba73e7";
        // 客户密钥
        final String customerSecret = "2a3da0d0a1cd4183bb0aadf2f471b71c";

        // 拼接客户 ID 和客户密钥并使用 base64 编码
        String plainCredentials = customerKey + ":" + customerSecret;
        String base64Credentials = new String(Base64.getEncoder().encode(plainCredentials.getBytes()));
        // 创建 authorization header
        String authorizationHeader = "Basic " + base64Credentials;

        return authorizationHeader;
    }

    /**
     * 获取指定项目的用量数据
     */
    @Override
    public UsageResp getUsageList(String projectId, String fromDate, String toDate, String business) {
        UsageResp usageResp = new UsageResp();
        try {
            String resp = HttpUtil.doGetWithHead("https://api.agora.io/dev/v3/usage?project_id=" + projectId + "&from_date=" + fromDate + "&to_date=" + toDate + "&business=" + business, getAuthorization());
            usageResp = JSON.parseObject(resp, UsageResp.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return usageResp;
    }

    /**
     * 创建封禁用户权限规则
     */
    @Override
    public MessageResp createKickingRule(KickingRuleDTO dto) {
        MessageResp messageResp = new MessageResp();
        try {
            String resp = HttpUtil.doPostWithHead(JSON.toJSONString(dto), "https://api.agora.io/dev/v1/kicking-rule", getAuthorization());
            messageResp = JSON.parseObject(resp, MessageResp.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return messageResp;
    }

    /**
     * 获取封禁用户权限规则列表
     */
    @Override
    public RuleResp getKickingRule(String appId) {
        RuleResp ruleResp = new RuleResp();
        try {
            String resp = HttpUtil.doGetWithHead("https://api.agora.io/dev/v1/kicking-rule?appid=" + appId, getAuthorization());
            ruleResp = JSON.parseObject(resp, RuleResp.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ruleResp;
    }

    /**
     * 更新封禁用户权限规则的生效时间
     */
    @Override
    public MessageResp editKickingRule(EditRuleDTO dto) {
        MessageResp messageResp = new MessageResp();
        try {
            String resp = HttpUtil.doPut(JSON.toJSONString(dto), "https://api.agora.io/dev/v1/kicking-rule", getAuthorization());
            messageResp = JSON.parseObject(resp, MessageResp.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return messageResp;
    }

    /**
     * 删除封禁用户权限规则
     */
    @Override
    public MessageResp deleteKickingRule(DeleteRuleDTO dto) {
        MessageResp messageResp = new MessageResp();
        try {
            String resp = HttpUtil.doDelete(JSON.toJSONString(dto), "https://api.agora.io/dev/v1/kicking-rule", getAuthorization());
            messageResp = JSON.parseObject(resp, MessageResp.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return messageResp;
    }

    /**
     * 查询用户状态
     */
    @Override
    public UserPropertyDTO getUserStatus(String appid, Long uid, String channelName) {
        UserPropertyDTO data = new UserPropertyDTO();
        try {
            String resp = HttpUtil.doGetWithHead("https://api.agora.io/dev/v1/channel/user/property/" + appid + "/" + String.valueOf(uid) + "/" + channelName, getAuthorization());
            ChannelMessageResp channelMessageResp = JSON.parseObject(resp, ChannelMessageResp.class);
            if (channelMessageResp.getSuccess()) {
                data = JSON.parseObject(String.valueOf(channelMessageResp.getData()), UserPropertyDTO.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 获取用户列表
     */
    @Override
    public ChannelUserDTO getChannelUser(String appid, String channelName) {
        ChannelUserDTO data = new ChannelUserDTO();
        try {
            String resp = HttpUtil.doGetWithHead("https://api.agora.io/dev/v1/channel/user/" + appid + "/" + channelName, getAuthorization());
            ChannelMessageResp channelMessageResp = JSON.parseObject(resp, ChannelMessageResp.class);
            if (channelMessageResp.getSuccess()) {
                data = JSON.parseObject(String.valueOf(channelMessageResp.getData()), ChannelUserDTO.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 分页查询项目的频道列表
     */
    @Override
    public ChannelPageDTO getChannelPage(ChannelPageReq req) {
        ChannelPageDTO data = new ChannelPageDTO();
        try {
            String url = "https://api.agora.io/dev/v1/channel/" + req.getAppid();
            if (req.getPage_no() != null && req.getPage_size() != null) {
                url = "https://api.agora.io/dev/v1/channel/" + req.getAppid() + "?page_no=" + req.getPage_no() + "&page_size=" + req.getPage_size();
            }
            String resp = HttpUtil.doGetWithHead(url, getAuthorization());
            ChannelMessageResp channelMessageResp = JSON.parseObject(resp, ChannelMessageResp.class);
            if (channelMessageResp.getSuccess()) {
                data = JSON.parseObject(String.valueOf(channelMessageResp.getData()), ChannelPageDTO.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 获取录制资源id
     */
    @Override
    public String getRecordingResources(RecordingResourcesReq req) {
        String resourceId = "";
        String url = "https://api.agora.io/v1/apps/" + appid + "/cloud_recording/acquire";
        try {
            String resp = HttpUtil.doPostWithHead(JSON.toJSONString(req), url, getAuthorization());
            JSONObject jsonObject = JSON.parseObject(resp);
            resourceId = (String) jsonObject.get("resourceId");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resourceId;
    }

    /**
     * 开始录制
     */
    @Override
    public StartRecordResp startRecord(StartRecordReq req) {
        StartRecordResp startRecordResp = new StartRecordResp();
        String url = "https://api.agora.io/v1/apps/" + appid + "/cloud_recording/resourceid/" + req.getResourceid() + "/mode/" + req.getMode() + "/start";
        try {
            String resp = HttpUtil.doPostWithHead(JSON.toJSONString(req.getStartRecordDTO()), url, getAuthorization());
            if(StringUtils.isEmpty(resp)){
                log.error("开始直播失败");
            }
            startRecordResp = JSON.parseObject(resp, StartRecordResp.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return startRecordResp;
    }

    /**
     * 结束录制
     */
    @Override
    public StopRecordResp stopRecord(StopRecordReq req) {
        String url = "https://api.agora.io/v1/apps/" + appid + "/cloud_recording/resourceid/" + req.getResourceid() + "/sid/" + req.getSid() + "/mode/" + req.getMode() + "/stop";
        StopRecordResp stopRecordResp = new StopRecordResp();
        try {
            String resp = HttpUtil.doPostWithHead(JSON.toJSONString(req.getStopRecordDTO()), url, getAuthorization());
            if(StringUtils.isEmpty(resp)){
                log.error("结束直播失败");
            }
            stopRecordResp = JSON.parseObject(resp, StopRecordResp.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return stopRecordResp;
    }

    /**
     * 查询录制状态
     */
    @Override
    public QueryRecordResp queryRecord(QueryRecordReq req) {
        String url = "https://api.agora.io/v1/apps/" + appid + "/cloud_recording/resourceid/" + req.getResourceid() + "/sid/" + req.getSid() + "/mode/" + req.getMode() + "/query";
        QueryRecordResp queryRecordResp = new QueryRecordResp();
        try {
            String resp = HttpUtil.doGetWithHead(url, getAuthorization());
            if(StringUtils.isEmpty(resp)){
                log.error("结束直播失败");
            }
            queryRecordResp = JSON.parseObject(resp, QueryRecordResp.class);


        } catch (Exception e) {
            e.printStackTrace();
        }
        return queryRecordResp;
    }

    /**
     * 更新录制配置
     */
    @Override
    public UpdateRecordResp updateRecordConfig(UpdateRecordReq req) {
        String url = "https://api.agora.io/v1/apps/" + appid + "/cloud_recording/resourceid/" + req.getResourceid() + "/sid/" + req.getSid() + "/mode/" + req.getMode() + "/update";
        UpdateRecordResp updateRecordResp = new UpdateRecordResp();
        try {
            String resp = HttpUtil.doPostWithHead(JSON.toJSONString(req.getUpdateRecordDTO()), url, getAuthorization());
            updateRecordResp = JSON.parseObject(resp, UpdateRecordResp.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return updateRecordResp;
    }

    @Override
    public ProjectDTO editRecordConfigIp(String id, String recordingServer) {
        EditRecordConfigResp editRecordConfigResp = new EditRecordConfigResp();
        String url = "https://api.agora.io/dev/v1/recording_config";
        Map<String, String> paramMap = new TreeMap<>();
        paramMap.put("id", id);
        paramMap.put("recording_server", recordingServer);
        try {
            String resp = HttpUtil.doPostWithHead(JSON.toJSONString(paramMap), url, getAuthorization());
            editRecordConfigResp = JSON.parseObject(resp, EditRecordConfigResp.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return editRecordConfigResp.getProject();
    }
}
